<?php
namespace app\crmwx\controller;


use think\Request;
use think\Exception;
use app\crm\model\Staff as StaffModel;
class Wx extends \CrmwxController
{
    protected $appId;
    protected $secret;
    protected $error = [];
    public $memcacheName;
    protected $prefix = 'mikkle.wechat.access_token.';
    protected $cacheKey;
    protected $cache;
    protected $access_token;
    protected $retry=false;
    public $errCode = 0;
    public $errMsg = "";
    const API_TOKEN_GET = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?';
    const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com';
    const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
    const GET_TICKET_URL = '/ticket/getticket?';
    const AUTH_URL = '/token?grant_type=client_credential&';
    function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));

        return $imageAll;
    }
    public function downloadImage() {
        $mediaId = $_GET['mediaId'];
      
      
        $access_token =    $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$mediaId;
        //echo $url;die;
        $a = $this->downloadWeixinFile($url);

        $download_dir = ROOT_PATH . 'public' . DS . 'goods_images' . DS .'weixin';

        !is_dir($download_dir) and mkdir($download_dir, 0755, true);



        //加水印Bx
     
        $resource = fopen($download_dir."/$mediaId.jpg" , 'w');

        //将图片内容写入上述新建的文件

        fwrite($resource, $a['body']);

        //关闭资源
        fclose($resource);
      
        return json([
            'error'=>0,
            'data'=>[
                'url'=>DS . 'uploads' . DS .'goods_images'."/$mediaId.jpg",
                'size'=>$a['header']['size_download'],
                'name'=>$mediaId.".jpg",
                ]
        ]);

    }
    public function getSignPackage($url="",$at="") {
        if(!$url){
            $url=urlencode("http://xlt.shared123.cn");
        }
        $jsapiTicket = $this->getJsApiTicket($at);
        $timestamp = time();

        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => 'wxa75fd57348cec1d7',
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
         return json($signPackage);
    }
    //微信OA2
    public function login(){
        $StaffModel = new \app\crmindex\model\Staff();
        $code = $_GET['code'];
        $state = $_GET['state'];
        
        $access_token=$this->getAccessToken();
        $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}";
        $wrdataJson = $this->http_request($url);
        $user=json_decode($wrdataJson,true);
        if($user){
            if($user["errcode"]){
                return json($user);
            }else{
                $staff_id=$user["UserId"];
                $staff=db("crm_staff")->where(["staff_id"=>$staff_id])->find();
                $user["data"]=$staff;
                return json($user);
            }
        }else{
            return json(["errcode"=>-1,"errmsg"=>"发生异常"]);
        }
        

    }
    public function getcode(){
        $red=urlencode("http://xlt.shared123.cn/crmwx/Wx/getbackcode");
        $oauth2Url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa75fd57348cec1d7&redirect_uri={$red}&response_type=code&scope=snsapi_userinfo&agentid=1000003&state=Aze#wechat_redirect";
        echo $oauth2Url;
    }
    public function getbackcode(){
        $code = $_GET['code'];
        $state = $_GET['state'];
        print_r($_GET);
    }
     function http_request($url,$data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);

        curl_close($ch);
        return $output;

    }
    /**
     * 微信获取签名
     *接口地址 xlt.shared123.cn/crmindex/Wx/index
     *| 参数 | 参数类型 | 是否必须 | 备注 |
     *|url| var |1| 域名地址(该url为调用jssdk接口的url)|

     */
    public function  index(Request $request){
        $config = config('crmwx');
        $this->appId = $config["CORP_ID"];
        $this->secret = $config['APP_SECRET'];
        $this->memcacheName = 'js';
        try {
            $param =  delToken($request->param());

            $data = $this->getSignPackage($param['url']);

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }

    }


    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例

        $data = $this->getCacheTicket();

        if (empty($data)) {

            $accessToken = $this->getAccessToken();

            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=".$accessToken;

            $res = json_decode($this->httpGet($url));

            $ticket = $res->ticket;
            if ($ticket) {

                $this->setCacheTicket($ticket);
            }
        } else {
            $ticket = $data;
        }
        return $ticket;
    }

    public function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $config = config('crmwx');
        $this->appId = $config["CORP_ID"];
        $this->secret = $config['APP_SECRET'];
        $data =$this->getCacheToken($this->memcacheName);
        if (empty($data)) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?grant_type=client_credential&corpid=$this->appId&corpsecret=$this->secret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $this->setCacheToken($access_token,$this->memcacheName);
            }
        } else {
            $access_token = $data;
        }
        return $access_token;
    }

    private function httpGet($url) {

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1 );
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
        $res = curl_exec($ch);
        curl_close($ch);

        return $res;
    }

    private function httpsPost($url = '', $post_data = array()){
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

    //清除
    public function delMem(){
        $Memcache =  new \Memcache();

        $Memcache->connect('127.0.0.1','11211');
        $Memcache->flush();
    }
    private function getCacheToken($kName)
    {$ConNo = session('companyInfo.id');
        $Memcache =  new \Memcache();
        $Memcache->connect('127.0.0.1','11211');
        return $Memcache->get($ConNo.'wx'."_a_token_".$kName);
    }

    private function setCacheToken($token,$kName)
    {
        $ConNo = session('companyInfo.id');
        $Memcache =  new \Memcache();
        $Memcache->connect('127.0.0.1','11211');
        return  $Memcache->set($ConNo.'wx'."_a_token_".$kName,$token,false,7000);
    }
    private function getCacheTicket()
    {$ConNo = session('companyInfo.id');
        $Memcache =  new \Memcache();
        $Memcache->connect('127.0.0.1','11211');
        return  $Memcache->get($ConNo."_weixinqy_share_ticket_crm");  //缓存获取，也可自己放入数据库存储
    }

    private function setCacheTicket($ticket)
    {
        $ConNo = session('companyInfo.id');
        $Memcache =  new \Memcache();
        $Memcache->connect('127.0.0.1','11211');
        return $Memcache->set($ConNo."_weixinqy_share_ticket_crm",$ticket,false,7000);  //设置缓存
    }
    //==================================


}